package com.t282.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.t282.crm.entity.CstCustomer;
import com.t282.crm.pdfservice.PdfExportService;
import com.t282.crm.pdfservice.PdfExportServiceImpl;
import com.t282.crm.service.CstCustomerService;
import com.t282.crm.service.impl.CstCustomerServiceImpl;
import com.t282.crm.vo.CustomerQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("客户管理")
@Controller
@RequestMapping("/api/customer")
public class CustomerController {
    @Autowired
    private CstCustomerServiceImpl customerService;

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value = "查询客户信息，进行分页，多条件查询")
    @RequestMapping("/findByCustomerList")
    public String findByCustomerList(@RequestParam(defaultValue = "1") Integer index,@RequestParam(defaultValue = "5") Integer limit, CustomerQueryVo customerQueryVo, HttpServletRequest request){
        //构建分页构造器
        Page<CstCustomer> page = new Page<>(index,limit);
        //构建条件构造器
        QueryWrapper<CstCustomer> wrapper = new QueryWrapper<>();
        //判断条件是否为空
        if(null != customerQueryVo.getCustName() && !"".equals(customerQueryVo.getCustName())){//客户名称
            wrapper.like("cust_name",customerQueryVo.getCustName());
        }
        if(null != customerQueryVo.getCustNo() && !"".equals(customerQueryVo.getCustNo())){//客户编号
            wrapper.like("cust_no",customerQueryVo.getCustNo());
        }
        if(null != customerQueryVo.getCustRegion() && !"".equals(customerQueryVo.getCustRegion())){//地区
            wrapper.eq("cust_region",customerQueryVo.getCustRegion());
        }
        if(null != customerQueryVo.getCustManagerName() && !"".equals(customerQueryVo.getCustManagerName())){//负责人
            wrapper.eq("cust_manager_name",customerQueryVo.getCustManagerName());
        }
        if(null != customerQueryVo.getCustLevel() && !"".equals(customerQueryVo.getCustLevel())){//等级
            wrapper.eq("cust_level",customerQueryVo.getCustLevel());
        }
        //进行排序
        wrapper.orderByDesc("cust_level");

        //调用方法
        Page<CstCustomer> pages = customerService.page(page, wrapper);
        request.setAttribute("pages",pages);
        request.setAttribute("custName",customerQueryVo.getCustName());
        request.setAttribute("custNo",customerQueryVo.getCustNo());
        request.setAttribute("custRegion",customerQueryVo.getCustRegion());
        request.setAttribute("custManagerName",customerQueryVo.getCustManagerName());
        request.setAttribute("custLevel",customerQueryVo.getCustLevel());
        return "customer/list";
    }

    @ApiOperation("根据编号查询客户")
    @RequestMapping("getCustomerEdit")
    public String getCustomerEdit(String custNo,HttpServletRequest request){
        CstCustomer cstCustomer = customerService.getById(custNo);
        request.setAttribute("cstCustomer",cstCustomer);
        return "customer/edit";
    }

    @ApiOperation("编辑客户")
    @RequestMapping("/editCustomerEdit")
    public String editCustomerEdit(CstCustomer cstCustomer){
        boolean flag = customerService.updateById(cstCustomer);
        if(flag){
            return "redirect:/api/customer/findByCustomerList";
        }
        return "redirect:/api/customer/getCustomerEdit?custNo="+cstCustomer.getCustNo();
    }


    @ApiOperation(value = "查询客户信息，进行分页")
    @RequestMapping("/findByCustomer")
    public String findByCustomerList(@RequestParam(defaultValue = "1") Integer index,@RequestParam(defaultValue = "5") Integer limit,String custName, HttpServletRequest request){
        //构建分页构造器
        Page<CstCustomer> page = new Page<>(index,limit);
        //构建条件构造器
        QueryWrapper<CstCustomer> wrapper = new QueryWrapper<>();
        if(null != custName){
            wrapper.like("cust_name",custName);
        }
        wrapper.orderByDesc("cust_turnover");
        //调用方法
        Page<CstCustomer> pages = customerService.page(page,wrapper);
        request.setAttribute("pages",pages);
        request.setAttribute("custName",custName);
        return "charts/list";
    }

    @ApiOperation("查询客户贡献度")
    @RequestMapping("/findCustChieftain")
    @ResponseBody
    public Object findCustChieftain(){
        List<CstCustomer> list = customerService.list();
        return list;
    }

    @ApiOperation("导出为excel")
    @RequestMapping("/excel")
    public void excel(HttpServletResponse response){
        try {
            customerService.exportData(response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 导出接口
     * @return
     */
    @ApiOperation("导出为pdf")
    @GetMapping("/pdf")
    public ModelAndView exportPdf() {
        List<CstCustomer> manList = customerService.list();
        // 定义pdf视图
        View view = new PdfExportServiceImpl(exportService());
        ModelAndView mv = new ModelAndView();
        // 设置视图
        mv.setView(view);
        // 加入数据模型
        mv.addObject("manList", manList);
        return mv;
    }
    /**
     * 导出pdf自定义，每个控制器可以实现自己的导出逻辑
     * @return
     */
    @SuppressWarnings("unchecked")
    public PdfExportService exportService() {
        // 使用Lambda表达式
        return(model, document, writer, request, response)-> {
            try {
                // A4纸张
                document.setPageSize(PageSize.A4);
                // 标题
                document.addTitle("客户信息");
                // 换行
                document.add(new Chunk("\n"));
                // 表格，23列
                PdfPTable table = new PdfPTable(9);
                // 单元格
                PdfPCell cell = null;
                // 字体，定义为蓝色加粗
                Font f8 = new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED));
                f8.setColor(Color.BLUE);
                f8.setStyle(Font.BOLD);
                f8.setFamily("Arial,Verdana,Sans-serif");
                // 标题
                cell = new PdfPCell(new Paragraph("客户编号", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);
                // 标题
                cell = new PdfPCell(new Paragraph("客户名称", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("客户地区", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("负责人编号", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("负责人名称", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("等级编号", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("等级名称", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("年营业额", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);

                // 标题
                cell = new PdfPCell(new Paragraph("状态", f8));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                // 将单元格加入表格
                table.addCell(cell);


                // 获取数据模型中的manList
                List<CstCustomer> manList = (List<CstCustomer>)model.get("manList");
                for(CstCustomer man:manList) {
                    document.add(new Chunk("\n"));
                    cell = new PdfPCell(new Paragraph(man.getCustNo()+ "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustName() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustRegion() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustManagerId() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustManagerName() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustLevel() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustLevelLabel() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustTurnover() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));
                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getCustStatus() + "", new Font(BaseFont.createFont(new ClassPathResource("/static/FZLTHK.TTF").getPath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED))));

                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);

                }
                // 文档中加入表格
                document.add(table);
            } catch(DocumentException | IOException e) {
                e.printStackTrace();
            }
        };
    }

    @ApiOperation(value = "删除客户信息")
    @RequestMapping("delete/{cust_no}")
    @ResponseBody
    public Object removeCustomer(@PathVariable String cust_no){
        QueryWrapper<CstCustomer> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_no",cust_no);
        CstCustomer customer = customerService.getOne(wrapper);
        String url = "http://localhost:8081/sale/api/order/delete/"+customer.getCustName();
        Map map = restTemplate.getForObject(url, Map.class);

        if(map.get("result").equals("成功")){
            boolean flag = customerService.remove(wrapper);
            if(flag){
                map.put("result",true);
            }else{
                map.put("result",false);
            }
            return map;
        }else{
            map.put("result",false);
            return map;
        }

    }

    @RequestMapping("/findHistOrders")
    public String findHistOrders(String custNo,String custName,HttpServletRequest request){
        request.setAttribute("custNo",custNo);
        request.setAttribute("custName",custName);
        return  "orders/list";
    }

    @ResponseBody
    @ApiOperation(("查看历史订单"))
    @PostMapping("findHistOrder")
    public Object findHistOrders(String custName,Integer index,Integer limit){
        String url = "http://localhost:8081/sale/api/order/findHistOrders/"+index+"/"+limit+"/"+custName;
        String customerMap = restTemplate.getForObject(url, String.class);
        return customerMap;
    }

    @RequestMapping("/getOrder")
    public String getOrder(Integer odrId,HttpServletRequest request){
        request.setAttribute("odrId",odrId);
        return "orders/view";
    }

    @ResponseBody
    @ApiOperation(("查看订单详情"))
    @PostMapping("getOrders")
    public Object getOrders(Integer oddId){
        String url = "http://localhost:8081/sale/api/order/getOrders/"+oddId;
        String orderMap = restTemplate.getForObject(url, String.class);
        return orderMap;
    }
}
